import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;
import { Config } from '../Config';
import { UserGlobal } from '../Globals/UserGlobal';

@ccclass('QuickManager')
export class QuickManager extends Component {
    @property({ type: Node })
    public adoptCertNode: Node | null = null;

    private quicks: readonly Node[];

    start() {
        this.quicks = this.node.children;
        for (let i = 0; i < this.quicks.length; i++) {
            if (this.quicks[i].name == 'share') {
                this.quicks[i].on(Node.EventType.TOUCH_START, this.onShareClicked);
            } else if (this.quicks[i].name == 'certificate') {
                this.quicks[i].on(Node.EventType.TOUCH_START, this.onCeritificateClicked, this);
            }
        }

        setTimeout(() => {
            this.updateSprinkler();
        }, 500);
    }

    onShareClicked() {
        let config = new Config();
        window.location.href = config.shareUrl;
    }

    onCeritificateClicked() {
        this.adoptCertNode.active = true;
    }

    private sprinkler_frequency: number = 0;
    updateSprinkler() {
        if (this.sprinkler_frequency >= 10) {
            return;
        }
        this.sprinkler_frequency += 1;

        if (UserGlobal.instance._sprinklerNumber == 0) {
            setTimeout(() => {
                this.updateSprinkler();
            }, 500);
            return;
        }

        for (let i = 0; i < this.quicks.length; i++) {
            if (this.quicks[i].name == 'sprinkler') {
                this.showSprinkler(i);
            }
        }
    }

    showSprinkler(index: number) {
        let children = this.quicks[index].children;
        for (let i = 0; i < children.length; i++) {
            let _name = children[i].name;
            _name = _name.substring(9);
            if (parseInt(_name) == UserGlobal.instance._sprinklerNumber) {
                children[i].active = true;
            } else {
                children[i].active = false;
            }
        }
    }
}

